package io.kubesphere.devops.core;


import io.kubesphere.devops.model.UserMergingRule;

import java.util.concurrent.atomic.AtomicInteger;
/**
 *
 * <p> InheritableThread
 *
 * @author gaochuan
 * @since 2021/11/23
 * @version 0.1.0
 * @date 2021/11/23 10:47
 */
public class InheritableThread extends Thread implements Runnable {
    public static final String DEFAULT_NAME = "InheritableThread";
    private static final AtomicInteger created = new AtomicInteger();
    private final PartitionZone zone;
    private final UserMergingRule rule;

    public InheritableThread(Runnable r, PartitionZone zone,UserMergingRule rule) {
        this(r, DEFAULT_NAME, zone,rule);
    }

    public InheritableThread(Runnable runnable, String name, PartitionZone zone,UserMergingRule rule) {
        super(runnable, name + "-" + created.incrementAndGet());
        this.zone = zone;
        this.rule = rule;
    }

    @Override
    public void run() {
        try {
            DynamicDataSourceContextHolder.routePartition(zone, rule);
            super.run();
        } finally {
            DynamicDataSourceContextHolder.clearDataSourceKey();
        }
    }

}
